from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job

import json
from Tools.model_to_python import *
from . import models


def time_task():
    """定时的任务逻辑"""
    print("delete_stale_data")


def update_funds_job():
    '''
    更新基金的定时任务
    '''
    try:
        funds = models.Fund.objects.all()
        for fund in funds:
            update_script = fund.update_script
            print(update_script.script)
            exec(update_script.script)
            #print(type(update_script.script))
            #if(update_script.script == "print('aa')"):
            #    print("eq")
            #exec("print('aa')")
    except Exception as e:
        print(e)


started = False
def start():
    '''
    开启定时任务
    '''
    global started
    if started:
        return

    scheduler = BackgroundScheduler()  # 创建一个调度器对象
    scheduler.add_jobstore(DjangoJobStore(), "default")  # 添加一个作业
    try:
        # scheduler.add_job(time_task, 'cron', second = 10, id = 'time_task')
        scheduler.add_job(update_funds_job, 'interval', seconds = 20, id = 'update_funds_jos')
        register_events(scheduler)
        scheduler.start()
        # scheduler.remove_job(time_task)  # 移除定时任务    
        started = True
    except Exception as e:
        print(e)
        scheduler.shutdown()

